<%@ page import="java.util.Date, java.text.SimpleDateFormat" %>
<%@ page import="service.ClockService" %>
<%@ page import="service.impl.ClockServicelmpl" %>
<%@ page import="entity.ClockInRecord" %>
<%@ page import="entity.Student" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%
    ClockService clockService = new ClockServicelmpl();
    Student student= (Student) session.getAttribute("user");
    String studentId =student.getUser_id();
    boolean hasCheckedIn = false;
    String message = "";

    // 确保studentId不为空
    if (studentId == null) {
        message = "未获取到学生信息，请重新登录";
    } else {
        // 处理打卡请求
        if ("POST".equalsIgnoreCase(request.getMethod())) {
            try {
                ClockInRecord record = new ClockInRecord(studentId, new Date());
                boolean success = clockService.saveCheckIn(record);
                if (success) {
                    message = "打卡成功！";
                    hasCheckedIn = true;
                } else {
                    message = "今日已打卡，请勿重复操作";
                    hasCheckedIn = true;
                }
            } catch (Exception e) {
                message = "打卡失败：" + e.getMessage();
            }
        } else {
            // 检查今日是否已打卡
            try {
                hasCheckedIn = clockService.hasCheckedInToday(studentId);
                if (!hasCheckedIn) {
                    message = "今日尚未打卡，请及时打卡";
                }
            } catch (Exception e) {
                message = "获取打卡状态失败：" + (e.getMessage() != null ? e.getMessage() : "数据库查询错误");
            }
        }
    }
%>

<!DOCTYPE html>
<html>
<head>
    <title>每日打卡</title>
    <style>
        :root {
            --primary-color: #4a6bdf;
            --success-color: #4CAF50;
            --error-color: #f44336;
            --text-color: #333;
            --light-bg: #f8f9fa;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: rgb(255, 255, 255);
            color: var(--text-color);
            line-height: 1.6;
        }
        
        .checkin-container {
            max-width: 500px;
            margin: 40px auto;
            padding: 30px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }
        
        .checkin-container:hover {
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        
        h2 {
            text-align: center;
            color: var(--primary-color);
            margin-bottom: 25px;
            font-weight: 600;
        }
        
        .btn-checkin {
            display: block;
            width: 100%;
            padding: 12px;
            margin: 20px 0;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .btn-checkin:hover {
            background-color: #3a56c4;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        
        .btn-checkin:disabled {
            background-color: #cccccc;
            transform: none;
            box-shadow: none;
            cursor: not-allowed;
        }
        
        .message {
            margin: 15px 0;
            padding: 12px 15px;
            border-radius: 6px;
            font-weight: 500;
        }
        
        .success {
            background-color: rgba(76, 175, 80, 0.15);
            color: var(--success-color);
            border-left: 4px solid var(--success-color);
        }
        
        .error {
            background-color: rgba(244, 67, 54, 0.15);
            color: var(--error-color);
            border-left: 4px solid var(--error-color);
        }
        
        .time-display {
            font-size: 18px;
            margin: 20px 0;
            text-align: center;
            padding: 15px;
            background: rgba(74, 107, 223, 0.1);
            border-radius: 6px;
            color: var(--primary-color);
            font-weight: 500;
        }
        
        .status-display {
            margin-top: 25px;
            font-size: 16px;
            text-align: center;
            padding: 12px;
            background: #f8f9fa;
            border-radius: 6px;
            border: 1px solid #eee;
        }
        
        strong {
            color: var(--primary-color);
        }
        
        /* 添加动画效果 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .checkin-container {
            animation: fadeIn 0.5s ease-out;
        }
    </style>
    <script>
        // 更可靠的时间显示方案
        function displayTime() {
            try {
                const now = new Date();
                // 添加时区处理
                const timeStr = 
                    now.getFullYear() + '-' +
                    String(now.getMonth() + 1).padStart(2, '0') + '-' +
                    String(now.getDate()).padStart(2, '0') + ' ' +
                    String(now.getHours()).padStart(2, '0') + ':' +
                    String(now.getMinutes()).padStart(2, '0') + ':' +
                    String(now.getSeconds()).padStart(2, '0') + 
                    ' (北京时间)';
                
                const timeElement = document.getElementById('current-time');
                if (timeElement) {
                    timeElement.textContent = timeStr;
                } else {
                    console.error('无法找到current-time元素');
                    setTimeout(displayTime, 3000);
                }
            } catch (e) {
                console.error('时间显示错误:', e);
            }
        }
    
        // 确保DOM加载完成
        document.addEventListener('DOMContentLoaded', function() {
            console.log('页面加载完成，开始显示时间');
            displayTime(); // 立即显示
            setInterval(displayTime, 1000); // 每秒更新
        });
    </script>
</head>
<body>
<div class="checkin-container">
    <h2>每日打卡</h2>

    <% if (!message.isEmpty()) { %>
    <div class="message <%= message.contains("成功") ? "success" : "error" %>">
        <%= message %>
    </div>
    <% } %>

    <form id="clock-in-form">
        <div class="time-display">
            当前时间: <span id="current-time"></span>
        </div>
        <button type="button" class="btn-checkin" <%= hasCheckedIn ? "disabled" : "" %>>
            <%= hasCheckedIn ? "今日已打卡" : "确认打卡" %>
        </button>
    </form>

    <div class="status-display">
        今日打卡状态: <strong><%= hasCheckedIn ? "已完成" : "未完成" %></strong>
    </div>
</div>
</body>
</html>
<script>
document.querySelector('.btn-checkin').addEventListener('click', function(e) {
    e.preventDefault();
    
    const submitBtn = this;
    submitBtn.disabled = true;
    submitBtn.textContent = '打卡中...';
    
    fetch('<%=request.getContextPath()%>/clockController?op=checkIn', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'op=checkIn'
    })
    .then(response => response.text())
    .then(data => {
        const result = JSON.parse(data);
        if(result === "不在规定打卡时间段内") {
            alert("未在时间段内打卡，已记录异常");
            submitBtn.textContent = "未在时间段内打卡";
            submitBtn.disabled = true;
        } else if(result === "打卡成功") {
            alert("打卡成功！");
            submitBtn.textContent = "今日已打卡";
            submitBtn.disabled = true;
        } else {
            alert(result);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('打卡失败');
        submitBtn.disabled = false;
        submitBtn.textContent = '确认打卡';
    });
});
</script>